package system.impl;

import java.util.ArrayList;
import java.util.HashMap;

import main.client.Client;
import main.client.Command;



public class SingleRequestClient extends Client {

	private SingleRequestClient() {
		super();
	}
	
	public SingleRequestClient(SingleRequestClientNavigator navigator) {
		super(navigator);
	}
	
	ArrayList<String> commands = new ArrayList();
	
	@Override
	public String getCommand() {
		if(commands.size() == 0)
			return null;
		String command = commands.get(0);
		commands.remove(0);
		return command;
	}

	@Override
	public void exit() {

	}
 
	@Override
	public void gotResult(Command command) {
		System.out.println("SingleRequestClient" + command.getName() + " gotResult: " + command.getReturnMap());
		gotResultListener.setResult(command.getReturnMap());
	}
	
	public GotResultListener gotResultListener = new GotResultListener();

	private class GotResultListener extends Thread {
		public GotResultListener() {
			start();
		}
		
		private HashMap result;

		public HashMap getResult() {
			while(result == null)
				try {
					Thread.sleep(1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			return result;
		}
		
		public void setResult(HashMap result) {
			this.result = result;
		}
		
		@Override
		public void run() {
			super.run();
		}

	}
	
	public HashMap runCommand(String command) {
		doCommand(command);
		return gotResultListener.getResult();
	}
	
}
